package com.xinnet.core.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;


/**
 * 网络程序工具类
 * @author 颜绿水
 * @author $Author:$
 * @version $Revision:$ $Date:$ 
 * @since 2014-7-7
 *
 */
public class INetUtils {

	/**
     * 获得本地的IP地址
     * 
     * @param
     * @return String IP地址
     */
    public static InetAddress getLocalNetAddress() {
        try {
            return getNet4Address();
        } catch (Exception ex) {
        }

        return null;
    }

    public static String getLocalHostAddress() {
        try {
            return getNet4Address().getHostAddress();
        } catch (Exception ex) {
        }

        return "";
    }

    private static InetAddress getNet4Address() throws UnknownHostException {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        if (!inetAddress.isLoopbackAddress()) {
                            return inetAddress;
                        }
                    }
                }
            }
        } catch (SocketException e) {
        }

        return InetAddress.getByName(null);
    }
    
    /**
     * 获取客户端请求公网ip地址 
     * @return
     */
    public static String getClientIpAddr(HttpServletRequest request) {
	     String ip = request.getHeader("x-forwarded-for");
	     if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
	         ip = request.getHeader("Proxy-Client-IP");
	     }
	     if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
	         ip = request.getHeader("WL-Proxy-Client-IP");
	     }
	     if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
	         ip = request.getRemoteAddr();
	     }
	     return ip;
	 }
    
    public static void main(String[] args) {
		System.out.println("local Ip: "+getLocalHostAddress());
	}
}
